<script setup>
import { ref , onMounted , computed} from 'vue';
import qs from 'qs'
import messageBox from './messageBox.vue';
import { useUserStore } from "../stores/user"
import islogin from "../api/isLogin.js"
import getChatList from '../api/getChatList';
import getChatVisited from "../api/getChatVisitedList.js"
import getUser from '../api/getuser.js'
import searchGroup from '../api/searchGroup.js'
import imageShow from './imageShow.vue';
const userInform = useUserStore()
import { ElLink, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {Search,Operation , CircleCloseFilled , Plus} from '@element-plus/icons-vue'
import sender from "../api/sendMessage.js"
import updateGroup from "../api/updateGroup.js"
import removeGroup from '../api/removeGroup.js';
import delGroup from '../api/delGroup.js'
import listen from '../api/startListenGroup.js'
import getRecommandGroup from '../api/getRecommandGroup.js'
import addGroup from '../api/addGroup.js'
import create from '../api/createGroup.js'
const image_id = ref("")
const imageUrl = ref("")
const chatLists= ref([])
const use = useRouter()
const chatBox = ref({})

const search_value = ref("")
const dialogVisible = ref(false)
const props =  defineProps({
    value:String
})
const activeName_2 = ref("1")
const url = "http://localhost:5173/api/image/upload?token=Bearer "+localStorage.getItem("jwttoken")
const message = ref("")
const visible = ref(false)
const activeName = ref('1')
const userId = ref(localStorage.getItem("userId"))
const showFlag = ref(false)
const groupSearchValue = ref([])
const recommand_group = ref([])
const visited_group = ref([])
const createGroup = ref({
    groupName:"",
    description:"",
    imageId:""
})

try{
        if(userInform.userId === ""){
        getUser({}).then(function (response) {
        console.log(userInform.userId);
        if(response.status == 200 && response.data.userId!=undefined)
        {
            userInform.userId = response.data.userId ;
            userInform.username = response.data.userName ;
            userInform.image = response.data.imageId;
            userInform.article =  response.data.articleId ;
        }
        else {
            localStorage.removeItem("jwttoken");
            localStorage.removeItem("userId");
            userInform.clear();
        }
        })
        }
    }
catch(error)
{
    loading.value = false ;
    console.error(error);
}   // 获取 user 并装配到 userinformstore 中 



onMounted(()=>{
    if (typeof (WebSocket) === 'undefined') {
    ElMessage.error('您的浏览器不支持WebSocket，无法获取数据')
    }
    listen().then((res) => {
        if(res.status == 200) {
        }
    })
    getRecommandGroup().then((res)=>{
        if(res.status == 200) {
            recommand_group.value = res.data
        }
    })
    getChatVisited().then((res)=>{
        if(res.status == 200) {
            visited_group.value = res.data
        }
    })
    

}) 
const disabled = computed(() => loading.value || noMore.value)
let pageNum =  0 ;
const sizeNum = 10;
const bt_flag = ref(true) 
const hasError = ref(false)
const loading = ref(false)
const noMore = ref(false)

const load = () => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        search_Groups()
    }, 2000)
}

function search_Groups() {
    searchGroup({
        groupName:search_value.value,
        size:sizeNum,
        page:pageNum
    }).then((res)=>{
        if(res.status == 200 && res.data != "")
        {
            console.log(res.data)
            for(let item of res.data)
            groupSearchValue.value.push(item)
            noMore.value = false
            pageNum++
        }
        else
        {
            noMore.value = true
        }
    })
}

// 切换访问栏

function senderMsg(){
    if(message.value.trim !== "")
    {
        
        sender({
            "groupId":chatBox.value.id,
            "content":message.value,
            "userId":userInform.userId,
            "replay":"",
            "atUser": "",
            "timestamp":""
        }).then((res)=>{
            if(res.status == 200)
            {
                message.value = ""
            }
        })
    }
    // POST http://localhost:8080/messages
}  // 发送信息 

const image_id_create = ref("")
function successHandler_2 (res,file){
    createGroup.value.imageId = res
    image_id_create.value = res
    }

    function successHandler (res,file){
    createGroup.value.imageId = res
    image_id.value = res
    imageUrl.value= chatBox.imageId
    }


    function beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 5;

        if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 5MB!');
        }


        return isJPG && isLt2M;
        }

const messages = ref([])

let ws = new WebSocket("ws://localhost:5173/websocket/"+localStorage.getItem("userId")+"?token=Bearer "+localStorage.getItem("jwttoken"))

ws.onopen = function(){

    ElMessage.success("已连接上websocket")
    if(sessionStorage.getItem("message") != undefined)
    messages.value = JSON.parse(sessionStorage.getItem("message"))
}

ws.onerror = function () {
    ElMessage.error('websocket连接异常，请稍候重试')
    errorCallback()
}

function errorCallback(){
    use.back()
}

ws.onmessage = function(e){
    let data = JSON.parse(e.data)
    if(data){
        messages.value.push (data)
        sessionStorage.setItem("message", JSON.stringify(messages.value))
    }
}   // ws 的操作
console.log(message.value)
islogin().then((res)=>{
    if(res.status == 200 && res.data == true )
    {
        getChatList().then((res) => {
        if(res.status == 200)
        {
            chatLists.value = res.data
            if(chatLists.value != undefined)
            chatBox.value = chatLists.value[0]
            flagSet()
        }
        else{
            chatLists.value = []
        }  
        })
    }

    else use.back()  // 未登录直接返回
})    //判断是否登录 并获得chatlist 

function toChatBox(item){
    chatBox.value = item
    console.log(chatBox)
    if(chatBox.value != null)
    flagSet()
}

function flagSet(){
    showFlag.value = false;
    console.log(chatBox.value)
    if(chatBox.value!= undefined)
    { 
        for(let item of chatBox.value.adminId)
    {
        console.log(item)
        if(userId.value == item)
            showFlag.value = true
        break ;
    } }
}

function update(){
    updateGroup(chatBox.value).then((res)=>{
        if(res.status == 200)
        {
            chatBox.value = res.data
        }
        else
        ElMessage("更新失败")
    })
}

function addGroupById( id )
{
    addGroup(id).then((res)=>{
        if(res.status == 200)
        ElMessage.success("加入成功")
        else
        ElMessage.warning("检查是否已经加入，或群组状态异常")
    })
}

function removeAdmin(id){
    console.log(userId.value)
    if(id != userId.value)
        { chatBox.value.adminId = chatBox.value.adminId.filter(function(item) {
        return item !== id
        })
        ElMessage.success("已移除管理员:"+id)
        }
    else ElMessage("你不能移除自己")
    update();
}
function addAdmin(id){
    chatBox.value.adminId.push(id)
    ElMessage.success("已设置管理员:"+id)
    update()
}

function delUser(id){
    if(id != userId.value)
    {
    chatBox.value.userId = chatBox.value.userId.filter(function(item) {
        return item !== id
    })
    chatBox.value.adminId = chatBox.value.adminId.filter(function(item) {
        return item !== id
    })
    update()}
    else {
        ElMessage("你不能移除自己")
    }
}



function removeTheGroup(){
    if(userId.value != chatBox.value.belongsUser)
    removeGroup(chatBox.value.groupId)
    else {
        ElMessageBox.confirm('你的退出会导致群组的解散', 'Warning',
        {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
        }).then(() => {
        delGroup(chatBox.value.groupId)
        chatBox.value.status = false
        update()
        ElMessage({
            type: 'success',
            message: '已解散',
        })
        }).catch(() => {
        })
        
    }
}

function search_btn(){
    dialogVisible.value = true
    activeName_2.value = "2"
    pageNum = 0
    groupSearchValue.value = []
    search_Groups()

}

function create_btn(){
    create(createGroup.value).then((res)=>{
        if(res.status == 200)
        {
            use.go()
        }
    })
}
</script>
<template>

    <!-- char-area -->
    <section class="message-area">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <div class="chat-area">
                        <!-- chatlist -->
                        <div class="chatlist">
                            <div class="modal-dialog-scrollable">
                                <div class="modal-content">
                                    <div class="chat-header">
                                        <div class="msg-search">
                                            <input type="text" class="form-control" id="inlineFormInputGroup" placeholder="Search" aria-label="search"  @keydown.enter.native="search_btn" v-model="search_value">
                                            <el-button @click="search_btn()" :icon="Search" circle @submit.native.prevent/>   
                                        </div>

                                        <ul class="nav nav-tabs" id="myTab" role="tablist" style="margin-top: 10px;">
                                                <li class="nav-item" style="margin-left: 15%;">
                                                    <el-button @click="dialogVisible = true" text class>群组</el-button> 
                                                </li>
                                                <li class="nav-item" >
                                                    <el-button @click="use.push('/')" text class>返回</el-button> 
                                                </li>
                                        </ul>
                                    </div>

                                    <div class="modal-body">
                                        <!-- chat-list -->
                                        <div class="chat-lists">
                                            <div class="tab-content" id="myTabContent">
                                                <div class="tab-pane fade show active" id="Open" role="tabpanel" aria-labelledby="Open-tab">
                                                    <!-- chat-list -->
                                                    <div class="chat-list" v-for="item in chatLists">
                                                        <a href="#" class="d-flex align-items-center" @click="toChatBox(item)">
                                                            <div class="flex-shrink-0">
                                                                <imageShow :value="item.imageId" class="imageBox"></imageShow>
                                                                <span class="active"></span> 
                                                                <!-- 是否在线 -->
                                                            </div>
                                                            <div class="flex-grow-1 ms-3">
                                                                <h3>{{ item.groupName }}</h3>
                                                                <p> {{ item.description}}   </p>
                                                            </div>
                                                        </a>


                                                    </div>
                                                    <!-- chat-list -->
                                                </div>
                                                <div class="tab-pane fade" id="Closed" role="tabpanel" aria-labelledby="Closed-tab">
                                                    <!--closed box -->
                                                    <!-- chat-list -->
                                                    <div class="chat-list">
                                                        
                                                    </div>
                                                    <!-- chat-list -->
                                                </div>
                                            </div>
                                        </div>
                                        <!-- chat-list -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- chatlist -->


                        <!-- chatbox -->
                        <div class="chatbox">
                            <div class="modal-dialog-scrollable">
                                <div class="modal-content">
                                    <div class="msg-head">
                                        <div class="row">
                                            <div class="col-8">
                                                <div class="d-flex align-items-center">
                                                    <span class="chat-icon">
                                                        <img class="img-fluid" src="https://mehedihtml.com/chatbox/assets/img/arroleftt.svg" alt="image title"></span> 
                                                    <div class="flex-grow-1 ms-3">
                                                        <h3>{{chatBox.groupName}}</h3>
                                                        <p>{{chatBox.description}}</p>
                                                    </div>
                                                    <div class="ms-2" style="position: relative; right: -50%; ">
                                                        <el-button :icon="Operation" circle size="large" @click="visible = true"/>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-4">
                                                <ul class="moreoption">
                                                    <li class="navbar nav-item dropdown">
                                                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="fa fa-ellipsis-v" aria-hidden="true"></i></a>
                                                        <ul class="dropdown-menu">
                                                            <li><a class="dropdown-item" href="#">Action</a></li>
                                                            <li><a class="dropdown-item" href="#">Another action</a></li>
                                                            <li>
                                                                <hr class="dropdown-divider">
                                                            </li>
                                                            <li><a class="dropdown-item" href="#">Something else here</a></li>
                                                        </ul>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>


                                    <div class="modal-body">
                                        <div class="msg-body" >
                                            <ul style="overflow: auto; display: flex;flex-direction: column-reverse;" v-for="item in messages">
                                                <li class= " repaly " v-if="item.userId == userId && item.groupId == chatBox.id">
                                                    <p> {{ item.content }} </p>
                                                    <span class="time"> user: <el-link type="primary" style="font-size: 12px;" @click="use.push('/selfInform?userId='+item.userId)"><getUsername :value="item.userId"></getUsername></el-link> sendTime: {{item.timestamp }} </span>
                                                </li>
                                                <li class= " sender " v-if="item.userId != userId && item.groupId == chatBox.id">
                                                    <p> {{ item.content }} </p>
                                                    <span class="time"> user: <el-link type="primary" style="font-size: 12px;" @click="use.push('/selfInform?userId='+item.userId)"><getUsername :value="item.userId"></getUsername></el-link> sendTime: {{item.timestamp }} </span>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>


                                    <div class="send-box" @keydown.enter.native="senderMsg">
                                        <form onsubmit="return false;">
                                            <input type="text" class="form-control" aria-label="message…" placeholder="Write message…" v-model="message">
                                            <button id="senderBtn" type="button" @click="senderMsg"><i class="fa fa-paper-plane" aria-hidden="true"></i> 发送</button>
                                        </form>

                                        <!-- <div class="send-btns">
                                            <div class="attach">
                                                <div class="button-wrapper">
                                                    <span class="label">
                                                        <img class="img-fluid" src="https://mehedihtml.com/chatbox/assets/img/upload.svg" alt="image title"> attached file 
                                                    </span><input type="file" name="upload" id="upload" class="upload-box" placeholder="Upload File" aria-label="Upload File">
                                                </div>

                                                <select class="form-control" id="exampleFormControlSelect1">
                                                    <option>Select template</option>
                                                    <option>Template 1</option>
                                                    <option>Template 2</option>
                                                </select>

                                                <div class="add-apoint">
                                                    <a href="#" data-toggle="modal" data-target="#exampleModal4"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewbox="0 0 16 16" fill="none"><path d="M8 16C3.58862 16 0 12.4114 0 8C0 3.58862 3.58862 0 8 0C12.4114 0 16 3.58862 16 8C16 12.4114 12.4114 16 8 16ZM8 1C4.14001 1 1 4.14001 1 8C1 11.86 4.14001 15 8 15C11.86 15 15 11.86 15 8C15 4.14001 11.86 1 8 1Z" fill="#7D7D7D"/><path d="M11.5 8.5H4.5C4.224 8.5 4 8.276 4 8C4 7.724 4.224 7.5 4.5 7.5H11.5C11.776 7.5 12 7.724 12 8C12 8.276 11.776 8.5 11.5 8.5Z" fill="#7D7D7D"/><path d="M8 12C7.724 12 7.5 11.776 7.5 11.5V4.5C7.5 4.224 7.724 4 8 4C8.276 4 8.5 4.224 8.5 4.5V11.5C8.5 11.776 8.276 12 8 12Z" fill="#7D7D7D"/></svg> Appoinment</a>
                                                </div>
                                            </div>
                                        </div> -->

                                    </div>
                                </div>
                            </div>
                        </div>


                    </div>
                    <!-- chatbox -->


                </div>
            </div>
        </div>
    </section>
    <!-- char-area -->
    <el-drawer v-model="visible" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
    <h1 :id="titleId" :class="titleClass"> {{ chatBox.groupName }} </h1>
    <el-button type="danger" @click="close">
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
        Close
    </el-button>
    </template>
    
    <h5> 群号:  <ElLink>{{ chatBox.id }}</ElLink> <el-button @click="copy()" text>复制</el-button></h5>
    <h6> 所属： <ElLink>{{ chatBox.belongsUser }}</ElLink></h6>
    <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="管理员列表" name="1">
        <div>
            <ol v-for="item in chatBox.adminId ">
                <li><ElLink>{{ item }}</ElLink> &nbsp; &nbsp;<el-link v-show="userId == chatBox.belongsUser" @click="removeAdmin(item)">移除管理员</el-link> &nbsp; &nbsp; <el-link v-show="userId == chatBox.belongsUser" @click="delUser(item)" type="error">移除</el-link> </li>
        </ol>
        </div>
        </el-collapse-item>
        <el-collapse-item title="用户列表" name="2">
            <div>
            <ol v-for="item in chatBox.userId ">
                <li><ElLink>{{ item }}</ElLink>&nbsp; &nbsp;<el-link v-show="userId == chatBox.belongsUser" @click="addAdmin(item)">设置管理员</el-link>&nbsp; &nbsp;<el-link v-show="showFlag" @click="delUser(item)" type="error">移除</el-link></li>
        </ol>
        </div>
        </el-collapse-item>
        <el-collapse-item title="设置" name="3" v-show="showFlag">
            <div>
                <nav><span>图片:</span>&nbsp;<br> 
                    
                        <el-upload
                        style="width: 100px; width: 100px;"
                        :action="url"
                        :on-success = "successHandler"
                        :before-upload="beforeAvatarUpload">
                        <imageShow v-if="chatBox.imageId" :value="chatBox.imageId" style="width: 100px; height: 100px;"></imageShow>
                        <el-icon v-else class="el-icon-plus" style="position: relative; left: 47px; top: 47px;"> <Plus></Plus> </el-icon>
                        <imageShow v-if="image_id" :value="chatBox.imageId" style="width: 100px; height: 100px; margin-left: 10px;"></imageShow>
                        </el-upload>
                </nav>
                <nav>
                    <span>群组名:</span>&nbsp;<el-input v-model="chatBox.groupName"></el-input>
                </nav>
                <nav>
                    <span>设置简介:</span>&nbsp;<el-input v-model="chatBox.description" type="textarea"></el-input>
                </nav>
                <br>
                <br>
                <nav>
                    <el-button @click="update()">
                        提交
                    </el-button>
                </nav>
            </div>
        </el-collapse-item>
        <el-collapse-item title="简介" name="5">
            <div class="descriptionBox">  {{ chatBox.description }}</div>
        </el-collapse-item>
    </el-collapse>
    <el-button type="danger" @click="removeTheGroup" > 退出 </el-button>
    </el-drawer>

    <el-drawer
    ref="drawerRef"
    v-model="dialogVisible"
    title="群组"
    :before-close="handleClose"
    direction="ltr"
    class="demo-drawer"
    >
        <el-collapse v-model="activeName_2" accordion>
        <el-collapse-item title="推荐" name="1">
            <div>
                <ul class="infinite-list" style="overflow: auto">
                <li style="margin-top: 3px;" v-for="item in recommand_group" >
                    <el-card>
                        <div style="display: flex;" @click="addGroupById(item.id)">
                            <imageShow style="width: 50px; height: 50px; border-radius: 50%;" :value="item.imageId"></imageShow>
                            <div style="margin-left: 2%;">
                                {{ item.groupName }}
                                <br>
                                <span style="font-size: 10px;"> 简介：{{ item.description }} </span>
                            </div>
                        </div>
                    </el-card>
                </li>
                </ul>
            </div>
        </el-collapse-item>
        <el-collapse-item title="搜索" name="2">
            <div>
                <el-input  @keydown.enter.native="search_btn()" v-model="search_value" style="width: 260px;"/>  <el-button @click="search_btn()" text>搜索</el-button>
            </div>
            <div v-if="groupSearchValue!=[]">
                <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto" :infinite-scroll-disabled="disabled">
                <li style="margin-top: 3px;" v-for="item in groupSearchValue" >
                    <el-card style="100%" @click="addGroupById(item.id)">
                        <div style="display: flex;">
                            <imageShow style="width: 50px; height: 50px; border-radius: 50%;" :value="item.imageId"></imageShow>
                            <div style="margin-left: 2%;">
                                {{ item.groupName }}
                                <br>
                                <span style="font-size: 10px;"> 简介：{{ item.description }} </span>
                            </div>
                        </div>
                    </el-card>
                </li>
                </ul>
            </div>
        </el-collapse-item>
        <el-collapse-item title="最近访问过" name="3">
            <div>
                <ul class="infinite-list" style="overflow: auto">
                <li style="margin-top: 3px;" v-for="item in visited_group" >
                    <el-card>
                        <div style="display: flex;">
                            <imageShow style="width: 50px; height: 50px; border-radius: 50%;" :value="item.imageId"></imageShow>
                            <div style="margin-left: 2%;">
                                {{ item.groupName }}
                                <br>
                                <span style="font-size: 10px;"> 简介：{{ item.description }} </span>
                            </div>
                        </div>
                    </el-card>
                </li>
                </ul>
            </div>
        </el-collapse-item>
        <el-collapse-item title="创建" name="4">
            <el-card >
                <div>
                <div> <span> 图片: </span>
                <el-upload
                        class="avatar-uploader"
                        :action="url"
                        :on-success = "successHandler_2"
                        :before-upload="beforeAvatarUpload">
                        <imageShow class="avatar" v-if="image_id_create" :value="createGroup.imageId" ></imageShow>
                        <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
                    </el-upload>
                </div>
                <br>
                <div> <span> 群组名： </span> <el-input v-model="createGroup.groupName"/></div>
                <br>
                <div> <span> 简介：<br> </span> <textarea v-model="createGroup.description"/></div>
                
                <br>
                <div>
                    <el-button @click="create_btn" text> 提交</el-button>
                </div>
            </div>
            </el-card>
        </el-collapse-item>
    </el-collapse>

    </el-drawer>
    
</template>
<style>
@import "../css/chat.css"
</style>